package com.alm.handle.service.impl;

import com.alm.common.core.domain.AjaxResult;
import com.alm.common.enums.CommandTypeEnum;
import com.alm.common.enums.ExceptionConditionEnum;
import com.alm.handle.core.domain.entity.SysDevCommand;
import com.alm.handle.core.domain.entity.rq.SendCommandRq;
import com.alm.handle.mapper.SysDevCommandMapper;
import com.alm.handle.service.ApiService;
import com.alm.handle.util.ByteUtils;
import com.alm.handle.util.DataUtils;
import com.alm.handle.util.SendMessage;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author ywy
 * @date 2024/8/23
 */
@Service
@Slf4j
public class ApiServiceImpl implements ApiService {

    @Resource
    private SysDevCommandMapper devCommandMapper;

    @Override
    public AjaxResult sendCommand(SendCommandRq rq) {
        // 传入数据校验
        AjaxResult valid = valid(rq);
        if(valid != null) {
            return valid;
        }
        // 异常条件配置命令
        if(StringUtils.equals(CommandTypeEnum.EXCEPTION_CONDITION.name(), rq.getCommandType())) {
            // 组装数据区
            String data = processDataArea(rq);
            // 命令
            String command = DataUtils.setCommand(rq.getDevMac(), "42", "91", data);
            log.info("向设备发送命令：{}", command);
            // 发送
            SendMessage.sendMessage(ByteUtils.hexStrToBytes(command), rq.getDevMac());
        }
        // 其他命令查询数据库
        else {
            String commandType = rq.getCommandType();
            SysDevCommand devCommand = devCommandMapper.selectOne(new QueryWrapper<SysDevCommand>().lambda().eq(SysDevCommand::getCommandType, commandType));
            if(devCommand == null) {
                return AjaxResult.buildCodeAndMsg(50003, "命令类型不正确");
            }
            // 组装
            String byteData = devCommand.getByteData();
            String realCommand = byteData.replace("A1A1A1A1A1A1", rq.getDevMac());
            // 发送命令
            SendMessage.sendMessage(ByteUtils.hexStrToBytes(realCommand), rq.getDevMac());
        }

        return AjaxResult.success();

    }

    /**
     * 组装数据字符串
     * @param rq
     * @return
     */
    private String processDataArea(SendCommandRq rq) {

        StringBuilder sb = new StringBuilder("06");
        // 电压上限
        if(rq.getVoltageMaximums() != null) {
            sb.append(ExceptionConditionEnum.VOLTAGE_MAXIMUMS.getValue());
            int voltageMax = rq.getVoltageMaximums() * 100;
            sb.append(String.format("%04x", voltageMax));
        }
        //电压下限
        if(rq.getVoltageMinimums() != null) {
            sb.append(ExceptionConditionEnum.VOLTAGE_MINIMUMS.getValue());
            int voltageMin = rq.getVoltageMinimums() * 100;
            sb.append(String.format("%04x", voltageMin));
        }
        // 电流上限
        if(rq.getCurrentMaximums() != null) {
            sb.append(ExceptionConditionEnum.CURRENT_MAXIMUMS.getValue());
            int currentMax = rq.getCurrentMaximums() * 1000;
            sb.append(String.format("%04x", currentMax));
        }
        // 电流下限
        if(rq.getCurrentMinimums() != null) {
            sb.append(ExceptionConditionEnum.CURRENT_MINIMUMS.getValue());
            int currentMin = rq.getCurrentMinimums() * 1000;
            sb.append(String.format("%04x", currentMin));
        }
        // 功率上限
        if(rq.getPowerMaximums() != null) {
            sb.append(ExceptionConditionEnum.POWER_MAXIMUMS.getValue());
            int powerMax = rq.getPowerMaximums() * 1000;
            sb.append(String.format("%08x", powerMax));
        }
        // 功率下限
        if(rq.getCurrentMinimums() != null) {
            sb.append(ExceptionConditionEnum.POWER_MINIMUMS.getValue());
            int powerMin = rq.getPowerMinimums() * 1000;
            sb.append(String.format("%08x", powerMin));
        }

        System.out.println(sb.toString());
        return sb.toString();
    }


    /**
     * 发送配置设备命令前校验
     * @param rq
     * @return
     */
    private AjaxResult valid(SendCommandRq rq){
        if(StringUtils.isBlank(rq.getDevMac())) {
            return AjaxResult.buildCodeAndMsg(50002, "设备mac地址为空");
        }
        if(StringUtils.isBlank(rq.getCommandType())) {
            return AjaxResult.buildCodeAndMsg(50003, "命令类型不正确");
        }
        // 如果设置异常条件
        if(StringUtils.equals(rq.getCommandType(), CommandTypeEnum.EXCEPTION_CONDITION.name())) {
            // 全为空的情况
            if(rq.getCurrentMaximums() == null && rq.getCurrentMinimums() == null && rq.getPowerMaximums() == null
                    && rq.getPowerMinimums() == null && rq.getVoltageMinimums() == null && rq.getVoltageMaximums() == null) {
                return AjaxResult.buildCodeAndMsg(50004, "需要设置的条件应至少有一个不为空");
            }
            // 校验电流上下限数据正确性
            if(rq.getCurrentMaximums() != null) {
                if(rq.getCurrentMaximums() < 0) {
                    return AjaxResult.buildCodeAndMsg(50011, "电流上下限设置不能为负数");
                }
                // 电流不能大于60A
                if(rq.getCurrentMaximums() > 60) {
                    return AjaxResult.buildCodeAndMsg(50020, "电流上限最大为60A");
                }
                if(rq.getCurrentMinimums() != null) {
                    if(rq.getCurrentMinimums() < 0) {
                        return AjaxResult.buildCodeAndMsg(50011, "电流上下限设置不能为负数");
                    }
                    if(rq.getCurrentMinimums() > rq.getCurrentMaximums()) {
                        return AjaxResult.buildCodeAndMsg(50010, "电流阈值设置不正确");
                    }
                }
            }
            if(rq.getCurrentMinimums() != null && rq.getCurrentMinimums() < 0) {
                return AjaxResult.buildCodeAndMsg(50011, "电流上下限设置不能为负数");
            }
            // 校验电压上下限数据正确性
            if(rq.getVoltageMaximums() != null) {
                if(rq.getVoltageMaximums() < 0) {
                    return AjaxResult.buildCodeAndMsg(50013, "电压上下限设置不能为负数");
                }
                // 电压不能大于600V
                if(rq.getVoltageMaximums() > 600) {
                    return AjaxResult.buildCodeAndMsg(50021, "电压上限最大为600V");
                }
                if(rq.getVoltageMinimums() != null) {
                    if(rq.getVoltageMinimums() < 0) {
                        return AjaxResult.buildCodeAndMsg(50013, "电压上下限设置不能为负数");
                    }
                    if(rq.getVoltageMinimums() > rq.getVoltageMaximums()) {
                        return AjaxResult.buildCodeAndMsg(50012, "电压阈值设置不正确");
                    }
                }
            }
            if(rq.getVoltageMinimums() != null && rq.getVoltageMinimums() < 0) {
                return AjaxResult.buildCodeAndMsg(50013, "电压上下限设置不能为负数");
            }
            // 校验功率上下限数据正确性
            if(rq.getPowerMaximums() != null) {
                if(rq.getPowerMaximums() < 0) {
                    return AjaxResult.buildCodeAndMsg(50014, "功率上下限设置不能为负数");
                }
                // 功率最大为3600W
                if(rq.getPowerMaximums() > 3600){
                    return AjaxResult.buildCodeAndMsg(50022, "功率上限最大为3600W");
                }
                if(rq.getPowerMinimums() != null) {
                    if(rq.getPowerMinimums() < 0) {
                        return AjaxResult.buildCodeAndMsg(50014, "功率上下限设置不能为负数");
                    }
                    if(rq.getPowerMinimums() > rq.getPowerMaximums()) {
                        return AjaxResult.buildCodeAndMsg(50015, "功率阈值设置不正确");
                    }
                }
            }

        }
        return null;
    }
}
